package com.uroad.jilinpda.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.load.engine.Resource;
import com.uroad.jilinpda.R;
import com.uroad.jilinpda.common.BaseActivity;
import com.uroad.jilinpda.common.CurrApplication;
import com.uroad.jilinpda.common.GlobalData;
import com.uroad.jilinpda.layer.MainLayer;
import com.uroad.jilinpda.modle.CheckVersionMDL;
import com.uroad.jilinpda.util.DownLoadUtils;
import com.uroad.jilinpda.util.SPUtils;
import com.uroad.jilinpda.webservice.ActivateWS;
import com.uroad.jilinpda.widget.TripDialog;
import com.uroad.lib.data.Constant;
import com.uroad.lib.json.FastJsonUtils;
import com.uroad.lib.util.log.LogUtil;
import com.uroad.lib.util.sys.SystemUtil;
import com.uroad.lib.widget.dialog.DialogHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.uroad.jilinpda.webservice.BaseWS.getNewUrl;

public class SettingActivity extends BaseActivity {

    @BindView(R.id.iv_network)
    ImageView iv_network;
    @BindView(R.id.iv_update_tipe)
    ImageView iv_update_tipe;
    @BindView(R.id.iv_power_up)
    ImageView iv_power_up;
    @BindView(R.id.tv_update)
    TextView tv_update;
    @BindView(R.id.iv_power_down)
    ImageView iv_power_down;
    @BindView(R.id.tv_power)
    TextView tv_power;
    private TripDialog tripDialog;
    private CheckVersionMDL mdl;
    private boolean isDownloading = false;
    private SingleDownloadTask downloadTask;
    private int power;
    private int tryTimes;
    private boolean result = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setBaseContentLayout(R.layout.activity_setting);
        ButterKnife.bind(this);
        setTitle("设置");
        setNet();
        init();
        getVersionInfo();
    }

    private void init(){
        tripDialog = new TripDialog(this);
        tripDialog.setDismissAble(false);
        power = (int) SPUtils.get(this, GlobalData.sp_power, 18);
        tv_power.setText(String.valueOf(power));
    }

    private void setNet(){
        if ("WIFI".equals(Constant.NET)){
            iv_network.setImageDrawable(getResources().getDrawable(R.mipmap.ic_network_wifi));
        }else if("4G".equals(Constant.NET)){
            iv_network.setImageDrawable(getResources().getDrawable(R.mipmap.ic_network_4g));
        }
    }

    @OnClick({R.id.iv_network, R.id.tv_update, R.id.iv_power_up, R.id.iv_power_down})
    public void onClick(View view) {
        switch (view.getId()){
            case  R.id.iv_network:
                if ("WIFI".equals(Constant.NET)){
                    Constant.NET = "4G";
                }else if("4G".equals(Constant.NET)){
                    Constant.NET = "WIFI";
                }
                setNet();
                SPUtils.put(this, GlobalData.sp_set_network, Constant.NET);
                break;
            case  R.id.tv_update:
                showDownloadDialog(mdl);
                break;
            case  R.id.iv_power_up:
                if (power<=30){
                    power++;
                    setPower();
                }
                break;
            case  R.id.iv_power_down:
                if (power >= 1) {
                    power--;
                    setPower();
                }
                break;
        }
    }

    //初始化天线模块 设置功率
    private void setPower() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    tryTimes = 5;
                    result = false;
                    CurrApplication.getInstance().openDsrc();
                    while (tryTimes-- > 0) {
                        result = CurrApplication.getInstance().getHandsetSDK().setDsrcTxPowerV2(0, power);
                        if (result) {
                            break;
                        }
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    CurrApplication.getInstance().closeDsrc();
                    if (result) {
                        runOnUiThread(updateThread);
                        SPUtils.put(SettingActivity.this, GlobalData.sp_power, power);
                        LogUtil.i("loginActivity", "天线模块设置成功");
                    }else{
                        LogUtil.i("loginActivity", "天线模块设置失败");
                    }
                } catch (Exception e) {
                    LogUtil.i("loginActivity", "天线模块设置异常："+e.getMessage());
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Runnable updateThread = new Runnable()
    {

        @Override
        public void run()
        {
            //更新UI
            tv_power.setText(String.valueOf(power));
        }

    };
    public void showDownloadDialog(CheckVersionMDL mdl) {
        if (mdl == null){
            return;
        }
        tripDialog.showCancelBtn(true);
        tripDialog.setTitle("发现新版本");
        tripDialog.setContent(mdl.getUpdatelog());
        tripDialog.setbtnConfirm("立即更新");
        tripDialog.setbtnCancel("稍后更新");
        tripDialog.setOnDialogClickListener(new TripDialog.OnDiglogClickListener() {
            @Override
            public void onConfirm() {
                downLoad(mdl.getDownloadurl());
            }

            @Override
            public void onCancel() {
                DialogHelper.endLoading();
                tripDialog.dismiss();
                //                if (isShowUpdateDialog) {
                //                    if (isMustUpdate) {
                //                        finish();
                //                        System.exit(0);
                //                    }
                //                }
            }
        });
        tripDialog.show();
    }

    public void getVersionInfo() {
        String deviceuuid = CurrApplication.getInstance().getDeviceuuid();
        doRequest(ActivateWS.appVersion, ActivateWS.appVersionParams(deviceuuid, "HANDSET"), ActivateWS.appVersion);
    }

    public void downLoad(String urlString){
        if (TextUtils.isEmpty(urlString)) {
            showShortToast("更新链接错误");
        } else {
            if ("4G".equalsIgnoreCase(Constant.NET)) {
                showShortToast("当前为4G网络，请连接WIFI并切换成外网后更新");
                return;
            }
            if (!isDownloading) {
                isDownloading = true;
                startDownload(urlString);
            }
        }
    }
    @Override
    public void OnHttpTaskComplete(String result, String id) {
        super.OnHttpTaskComplete(result, id);
        JSONObject jsonObject = JSONObject.parseObject(result.toString());
        if (FastJsonUtils.GetJsonStatu1(jsonObject)) {
            if (ActivateWS.appVersion.equalsIgnoreCase(id)) {
                //检查版本更新
                String data = FastJsonUtils.getData(jsonObject);
                mdl = FastJsonUtils.parseObjectJSON(data, CheckVersionMDL.class);
                if (mdl != null) {
                    String version = CurrApplication.getInstance().appversion;
                    if (SystemUtil.isNeedUpdate(version, mdl.getVersion())) {
                        iv_update_tipe.setVisibility(View.VISIBLE);
                    }else{
                        iv_update_tipe.setVisibility(View.GONE);
                    }
                }
            }
        }else{
              showShortToast(jsonObject.getString("msg"));
        }
    }

    private void startDownload(String urlString) {
        //方法二、使用http方式异步下载
        if (downloadTask != null && downloadTask.getStatus()== AsyncTask.Status.RUNNING) {
            return;
        }
        downloadTask = new SingleDownloadTask(urlString);
        downloadTask.execute();
    }

    public class SingleDownloadTask extends AsyncTask<String, Integer, String> {
        private File file;
        String urlString;

        public SingleDownloadTask(String urlString){
            this.urlString = urlString;
        }

        @Override
        protected String doInBackground(String... strings) {
            try {
                String fileName = urlString.substring(urlString.lastIndexOf("/")+1);
//                String fileName = "liaoningposcharge.apk";
                String filePath = Environment.getExternalStorageDirectory()+ File.separator + fileName;
                //新建要写入的文件
                file = new File(filePath);
                //如果文件不存在，则新建文件
                if (!file.exists()) {
                    file.createNewFile();
                }else{
                    file.delete();
                    file.createNewFile();
                }
                //获取url路径
                URL url = new URL(urlString);
                //获取url连接
                URLConnection connection = url.openConnection();
//                connection.setConnectTimeout(10 * 1000);
                //获取文件的总长度
                int length = connection.getContentLength();
                //				//显示文件大小
                //				Message msg = new Message();
                //				msg.what = length;
                //				handler.sendMessage(msg);
                //获取输入流
                InputStream is = connection.getInputStream();

                //获取输出流
                FileOutputStream os = new FileOutputStream(file);
                //通过字节读取，每次读取1024B
                byte[] array = new byte[1024];
                int sum = 0;
                int index = is.read(array);
                while (index != -1) {
                    //写出array，长度0-index
                    os.write(array, 0, index);
                    sum+=index;
                    //更新进度
                    publishProgress(sum, length);
                    index = is.read(array);
                }
                os.flush();
                os.close();
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
                file.delete();
                return "";
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            //更新下载进度
            long progress = (long) values[0] * 100 / (long) values[1];
            tripDialog.setContent("新版本下载中:"+progress+"%");
            //            tv_content.setText(progress+"%");
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            tripDialog.dismiss();
            isDownloading = false;
            //下载完成 运行下载文件
            //            tv_ok.setText("下载完成");
            //            tv_ok.setEnabled(true);
            if (file != null && file.length() > 0) {
                String path = file.getAbsolutePath();
                if (!TextUtils.isEmpty(path)) { //文件不为空，且下载完成
                    Intent intent = DownLoadUtils.openFile(path);
                    SettingActivity.this.startActivity(intent);

                    //                        int result = UpdateUtil.excuteSuCMD(path);
                    //                        if (result == 0) {
                    //                            LogUtil.d(TAG, "更新成功");
                    //                        } else {
                    //                            LogUtil.d(TAG, "更新失败");
                    //                        }
                }
            }else{
                LogUtil.d("posLoginActivity", "下载失败");
                showShortToast("下载失败，请稍后重试");
            }
        }
    }

}
